#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/10/19 10:12 AM
import datetime
import time

from rest_framework.authentication import TokenAuthentication
from rest_framework.exceptions import AuthenticationFailed

from social.exceptions import LogoutException
from social.token.models import Token


class WeFaceAuthentication(TokenAuthentication):
    keyword = 'Token'
    model = Token

    def authenticate_credentials(self, key):
        model = self.get_model()
        try:
            token = model.objects.select_related('user').only('user',
                                                              'expire_at',
                                                              'access_at',
                                                              'key').get(key=key)
        except model.DoesNotExist:
            raise AuthenticationFailed

        # if not token.user.is_active:
        #     raise LogoutException(msg="该账号已被禁止登陆")
        now = datetime.datetime.now()
        dur = now.timestamp() - token.user.last_active.timestamp()
        if dur >= 5 * 60:
            token.user.last_active = now
            token.user.save(update_fields=['last_active'])

        timestamp = int(time.time())
        if token.expire_at != 0:
            needs_save = False
            if token.expire_at < timestamp:
                raise LogoutException(msg="登录已过期，请重新登录")
            elif token.expire_at - timestamp < Token.MIN_EXPIRE_RENEW:
                token.expire_at += Token.MIN_EXPIRE_RENEW
                needs_save = True

            if timestamp - token.access_at >= Token.MIN_ACCESS_UPDATE_DURATION:
                token.access_at = timestamp
                needs_save = True

            if needs_save:
                token.save()

        return token.user, token


class IsGuardUser(WeFaceAuthentication):
    """
    Allows access only to admin users.
    """

    def has_permission(self, request, view):
        return bool(request.user and (request.user.is_guard or request.user.is_staff))
